Kotlin Koans 26 Sum

目次

Sum (Playground)

Description

Implement Customer.getTotalOrderPrice() using sum or sumBy.

sum もしくは sumBy を使用して、Customer.getTotalOrderPrice() を実装してください。

listOf(1, 5, 3).sum() == 9
listOf("a", "b", "cc").sumBy { it.length() } == 4

If you want to sum the double values, use sumByDouble.

Double型の値の合計を出したい場合は、sumByDouble を使用してください。

Code

// Return the sum of prices of all products that a customer has ordered.
// Note: the customer may order the same product for several times.
fun Customer.getTotalOrderPrice(): Double = orders.flatMap { it.products }.sumByDouble { it.price }

Memo

← Posts